
from struct import pack, unpack

def zerocode(bs):
    """zerocode a byte sequence"""
    o=""
    i=0
    amount = 0
    while i<len(bs):
        v = bs[i]
        if v=="\x00": # search more
            amount=1
            while i<len(bs):
                if bs[i+1]=="\x00":
                    amount+=1
                    i+=1
                else:
                    break
            o+="\x00"+pack(">b",amount)
        else:
            o+=v
        i+=1
    return o


def zerodecode(bs):
    """zerodecode a byte sequence"""
    o=""
    i=0
    while i<len(bs):
        v=bs[i]
        if v=="\x00":
            amount = unpack(">B",bs[i+1])[0]
            i+=1
            o+="\x00"*amount
        else:
            o+=v
        i+=1
    return o

def hexprint(s):
    from binascii import hexlify
    res=hexlify(s)
    i=0
    l=0
    import sys
    for r in res:
        sys.stdout.write(r)
        if i%4==3: 
            sys.stdout.write(" ")
        i+=1
        l+=1
        if l%32==0:
            sys.stdout.write("\n")
    print

    #block = msg.neighbourblock.new()
    #msg.neighbourblock[0].Test0 = 3 # block.Test0 = 3


def printUDP(s):
    """print with UDP/TCP dummy header"""
    l=28*(0,)
    s=pack(">"+28*'b', *l)+s
    return hexprint(s)

if __name__=="__main__":
    a=3
    s=pack(">q",a)
    print repr(s)
    print repr(zerocode(s))
    r=zerocode(s)
    print repr(zerodecode(r))
